from pylab import *
from scipy import optimize
from numpy import *

class Parameter:
    def __init__(self, value):
            self.value = value

    def set(self, value):
            self.value = value

    def __call__(self):
            return self.value

def fit(function, parameters, y, x = None):
    def f(params):
        return y - function(x)

    if x is None: x = arange(y.shape[0])
    p = [param() for param in parameters]
    return optimize.leastsq(f, p)


# giving initial parameters
mu = Parameter(7)
sigma = Parameter(3)
height = Parameter(5)
p = [mu, sigma, height]
# define your function:
def f(x): return height() * exp(-((x-mu())/sigma())**2)

# create test data
x0 = linspace(0., 20., 100)
data = f(x0)

# fit! (given that data is an array with the data to fit)
fitparas, sucess = fit(f, [mu, sigma, height], data, x0)
mu = Parameter(fitparas[0])
sigma = Parameter(fitparas[1])
height = Parameter(fitparas[2])
plot(x0, data, "bo", x0, f(x0), "r-")
show()
